package org.alicuu.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/06
 * Time: 18:21
 */
class DBConnectionPool {
    private static final int MIN_SIZE = DBManager.getConf().getPoolMinSize();
    private static final int MAX_SIZE = DBManager.getConf().getPoolMaxSize();
    private List<Connection> pool;

    DBConnectionPool() {
        initPool();
    }

    private void initPool() {
        if (pool == null)
            pool = new ArrayList<>();
        while (pool.size() < MIN_SIZE)
            pool.add(DBManager.createConnection());
    }

    synchronized Connection getConnection() {
        int lastIndex = pool.size() - 1;
        Connection connection = pool.get(lastIndex);
        pool.remove(lastIndex);
        return connection;
    }

    synchronized void close(Connection conn) {
        if (pool.size() >= MAX_SIZE) {
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else
            pool.add(conn);

    }
}
